package bean;

import frame.service.standard.CustomConfig;
import frame.service.standard.impl.CustomServiceHandler;
import http.MDCHttpFilter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import util.HttpUtil;
import util.SecurityUtil;
import util.SessionManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@EnableConfigurationProperties
public class BeanFactory implements InitializingBean {
    @Value("${app.config.service.customProcess:}")
    public List<String> customHandleServices;
    @Value("${app.config.sessionTimeout:15}")
    private int sessionTimeout;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ConfigurationProperties(prefix="app.config.http", ignoreUnknownFields = true)
    @Bean
    public HttpUtil.HttpParams httpParams(){
        return new HttpUtil.HttpParams();
    }

    @Bean
    public HttpUtil httpUtil(HttpUtil.HttpParams httpParams){
        return new HttpUtil(httpParams);
    }

    @Bean
    public FilterRegistrationBean registrationBean(){
        FilterRegistrationBean<MDCHttpFilter> bean = new FilterRegistrationBean<MDCHttpFilter>();
        bean.setFilter(new MDCHttpFilter());
        bean.setName("mdcHttpFilter");//过滤器名称
        bean.addUrlPatterns("/*");//过滤所有路径
        bean.setOrder(1);//优先级，最顶级
        return bean;
    }

    @Bean
    public CustomConfig customConfig(){
        CustomServiceHandler.services = customHandleServices;
        return new CustomServiceHandler();
    }

    @ConfigurationProperties(prefix="app.param.secure", ignoreUnknownFields = true)
    @Bean
    @Qualifier("secureParamsSource")
    public Map<String,String> loadSecureParams(){
        return new HashMap<String,String>();
    }

    @Bean
    @Qualifier("secureParams")
    public Map<String,String> secure(@Qualifier("secureParamsSource") Map<String,String> map){
        map.forEach((key, val)->{
            map.put(key, SecurityUtil.paramsDecrypt(val));
        });
        return map;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        SessionManager.setSessionTimeout(sessionTimeout);
        SessionManager.setStringRedisTemplate(stringRedisTemplate);
    }
}
